/**
 * 
 */
package mx.frantor.catalogos.daoimp;

import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import flex.messaging.io.ArrayCollection;

import mx.frantor.catalogos.bussines.MateriaPrimaExistenciasBussines;
import mx.frantor.catalogos.dao.DetallePedidoDAO;
import mx.frantor.catalogos.dao.MateriaPrimaExistenciasDAO;
import mx.frantor.catalogos.dao.ProductosExistenciaDAO;
import mx.frantor.catalogos.dao.RemMatPDAO;
import mx.frantor.catalogos.entitys.DetallePedidoEntity;
import mx.frantor.catalogos.entitys.MateriaPrimaExistenciasEntity;
import mx.frantor.catalogos.entitys.OrdenDeProduccionEntity;
import mx.frantor.catalogos.entitys.PedidosEntity;
import mx.frantor.catalogos.entitys.ProductosExistenciasEntity;
import mx.frantor.catalogos.entitys.RemMPEntity;
import mx.frantor.util.HibernateUtil;

/**
 * @author Hp
 *
 */
public class RemMPDAOImpl implements RemMatPDAO {
	
	private ProductosExistenciaDAO prodDAO = new ProductosExistenciaDAOImpl();
	private MateriaPrimaExistenciasDAO matPDAO = new MateriaPrimaExistenciasDAOImpl();
	private MateriaPrimaExistenciasBussines matPrimaBuss = new MateriaPrimaExistenciasBussines();

	/* (non-Javadoc)
	 * @see mx.frantor.catalogos.dao.DetallePedidoDAO#agregarDetallePedido(mx.frantor.catalogos.entitys.DetallePedidoEntity)
	 */
	@Override
	public String agregarRemMP(Long idDetallePedido,ArrayCollection catProds) {
		// TODO Auto-generated method stub
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

			String errRslt;
			try{
			
			//System.out.println("Size FlexCollection: " + reqUtil.size() + " Vals: " + reqUtil);
			String cantidadMP = null;
			String idProd = null;
			String idRefa = null;
			String idMatOld = null;
			String obs = null;
			String idMP = null;
			System.out.println(catProds.size());
			for(int i = 0; i < catProds.size(); i++){
				//StringTokenizer token = new StringTokenizer(String.valueOf(catProds.get(i).toString()),"=,");
				String[] token = catProds.get(i).toString().split(",");
				System.out.println(token.length);
				for(int a = 0; a < token.length; a++){
					System.out.println("entra while "+ token[a]);
					String[] b ;
					if(token[a].indexOf("idProd")!=-1){
						b = token[a].split("=");  
						idProd = b[1];
						System.out.println(idProd);
					}
					if(token[a].indexOf("idMP")!=-1){
						b = token[a].split("=");
						idMP=(b[1]);
					System.out.println(idMP);
					}
					if(token[a].indexOf("obs")!=-1){
						b = token[a].split("=");
						obs = b[1];
					System.out.println(obs);
					}
					if(token[a].indexOf("cantidad")!=-1){
						b = token[a].split("=");
						cantidadMP = b[1];
					System.out.println(cantidadMP);
					}
					if(token[a].indexOf("idOld")!=-1){
						b = token[a].split("=");
					idMatOld = b[1];
					System.out.println(idMatOld);
					}
					if(token[a].indexOf("idRefa")!=-1){
						b = token[a].split("=");
						idRefa= b[1];
						System.out.println(idRefa);
						if(!idRefa.equals("null")){
							idRefa= idRefa.substring(0, idRefa.length()-1);
						}
					}
				}
				
				
				
			
				RemMPEntity RemMat = new RemMPEntity();
					System.out.println("prod " + idProd + " d ped " + idDetallePedido + " cantidad " + cantidadMP + " Mp OLd " + idMatOld + " idmp " + idMP + " obs " + obs + " Refa "+ idRefa);
					if(!idProd.equals("null")){
						RemMat.setIdProducto(Long.valueOf(idProd));
					}
					System.out.println("1");
					RemMat.setIdDetallePedido(idDetallePedido);
					System.out.println("2");
					RemMat.setCantidad(Float.valueOf(cantidadMP));
					System.out.println("3");
					if(!idMatOld.equals("null")){
						RemMat.setIdMateriaOld(Long.valueOf(idMatOld));	
					}
					System.out.println("4");
					if(!idMP.equals("null")){
						RemMat.setIdMateria(Long.valueOf(idMP));
					}
					System.out.println("5");
					RemMat.setObservacion(obs);
					System.out.println("6");
					if(!idRefa.equals("null")){
						RemMat.setIdRefaccion(Long.valueOf(idRefa));
					}
					session.save(RemMat);
						
			}
			session.flush();
			session.getTransaction().commit();
			 //<--Realizamos commit de operacion en db
			 errRslt = "";
			
		
		}catch (Exception e) {
			
	  		session.getTransaction().rollback();
	  		errRslt = e.getMessage();
			System.out.println("Error en agrega Reemplazo con detalle implement: " + errRslt);
			
		}
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		System.out.println(errRslt);
		return errRslt;

	}

	/* (non-Javadoc)
	 * @see mx.frantor.catalogos.dao.DetallePedidoDAO#modificarDetallePedido(mx.frantor.catalogos.entitys.DetallePedidoEntity)
	 */
	@Override
	public String modificarRemMP(RemMPEntity modificarRemMP){
		// TODO Auto-generated method stub
		String e = "";
		Session session = HibernateUtil.getSessionFactory()
				.getCurrentSession();
	
		session.beginTransaction();
		try {
			RemMPEntity MPTemp = (RemMPEntity) session.get(
					RemMPEntity.class, modificarRemMP.getIdRem());
		session.flush();
		session.evict(MPTemp);
		session.update(modificarRemMP);
		session.getTransaction().commit();
		} catch (Exception x) {
			//e.printStackTrace();
			session.getTransaction().rollback();
			e = x.getMessage();
			//return e.toString();
		}
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		System.out.println("modificar Reemplazo Mat Prima resultado " + e);

		return e;
	}

	/* (non-Javadoc)
	 * @see mx.frantor.catalogos.dao.DetallePedidoDAO#eliminarDetallePedido(long)
	 */
	@Override
	public String  eliminarRemMP(long idRemMP){
		// TODO Auto-generated method stub
		String e = "";
		Session session = HibernateUtil.getSessionFactory()
				.getCurrentSession();
		

			// TODO Auto-generated method stub			
			session.beginTransaction();
			try {
				RemMPEntity MPpElimina = (RemMPEntity) session.get(
						RemMPEntity.class, idRemMP);
			session.delete(MPpElimina);
			session.getTransaction().commit();
		} catch (Exception x) {
			//e.printStackTrace();
			session.getTransaction().rollback();
			e = x.getMessage();
			//return e.toString();
		}
		//HibernateUtil.getSessionFactory().getCurrentSession().close();
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		System.out.println("eliminar rem mat p resultado " + e);

		return e;
	}

	/* (non-Javadoc)
	 * @see mx.frantor.catalogos.dao.DetallePedidoDAO#getTodosDetallePedidoActivos()
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<RemMPEntity> getTodosRemMPActivos() {
		// TODO Auto-generated method stub
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<RemMPEntity> dps = session.createCriteria(RemMPEntity.class)
				.addOrder(Order.asc("IdRem")).list();
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		return dps;	
	}

	/* (non-Javadoc)
	 * @see mx.frantor.catalogos.dao.DetallePedidoDAO#getDetallePedidoId(long)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public RemMPEntity getRemMPId(long idRemMP) {
		// TODO Auto-generated method stub
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<RemMPEntity> dps = (List<RemMPEntity>) session.createCriteria(RemMPEntity.class)
				.add(Restrictions.eq("IdRem", idRemMP)).list();
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		if(dps==null){
			return null;
		}else{
			return dps.get(0);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<RemMPEntity> getRemMPPorId(long idRemMP){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<RemMPEntity> usuario = (List<RemMPEntity>) session.createCriteria(RemMPEntity.class)
				.add(Restrictions.eq("IdDetallePedido", idRemMP))
				.list();
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		return usuario;
	}
	@Override
	public String cambiaEstatus(long idDetPedido, String estatus){
		String e = "";
		Session session = HibernateUtil.getSessionFactory()
				.getCurrentSession();
	
		session.beginTransaction();
		try {
			DetallePedidoEntity pedidosTemp = (DetallePedidoEntity) session.get(
					DetallePedidoEntity.class, idDetPedido );
		session.flush();
		session.evict(pedidosTemp);
		pedidosTemp.setEstatus(estatus);
		session.update(pedidosTemp);
		session.getTransaction().commit();
		} catch (Exception x) {
			//e.printStackTrace();
			session.getTransaction().rollback();
			e = x.getMessage();
			//return e.toString();
		}
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		System.out.println("modificar pedidos resultado " + e);

		return e;
	}
	public String agregarReemplazoProds(OrdenDeProduccionEntity ordProd, ArrayCollection catProds) {

		String errRslt = "";
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		try{
			
			session.save(ordProd);//<<---Guardamos en la DB
			long idDetallePedido = ordProd.getIdDetallePedido();
			//System.out.println("Size FlexCollection: " + reqUtil.size() + " Vals: " + reqUtil);
			String idProd;
			String cantidad;
			String idrefaccion;
			String idmateriaold;
			String idMP;
			String observacion;
			String aprov="n";
			System.out.println(catProds.size());
			for(int i = 0; i < catProds.size(); i++){
				StringTokenizer token = new StringTokenizer(String.valueOf(catProds.get(i).toString()),"=,");
				System.out.println(token.nextToken());
				System.out.println(token.nextToken());
				idProd=(token.nextToken());
				System.out.println(idProd);
				System.out.println(token.nextToken());
				cantidad = token.nextToken();
				System.out.println(cantidad);
				System.out.println(token.nextToken());
				idrefaccion = token.nextToken();
				System.out.println(idrefaccion);
				token.nextToken();
				token.nextToken();
				token.nextToken();
				token.nextToken();
				token.nextToken();
				idmateriaold= token.nextToken();
				System.out.println(idmateriaold);
				token.nextToken();
				idMP=token.nextToken();
				System.out.println(idMP);
				token.nextToken();
				observacion= token.nextToken();
				observacion= observacion.substring(0, observacion.length()-1);
				MateriaPrimaExistenciasEntity matPrimaE = new MateriaPrimaExistenciasEntity();
				if(idProd!= null){
					if(Float.valueOf(cantidad) >= prodDAO.getProductosExistenciasId(Long.valueOf(idProd)).getCantidad()){
						Float cant =prodDAO.getProductosExistenciasId(Long.valueOf(idProd)).getCantidad() - Float.valueOf(cantidad);
						matPrimaE.setCantidad(Float.valueOf(String.valueOf(cant)));
						matPrimaBuss.modificarMateriaPrimaExistenciasDirecto(matPrimaE);
						System.out.println("Materia Prima");
						aprov="s";
				}else{
					aprov="n";
					float f=Float.valueOf(cantidad)- prodDAO.getProductosExistenciasId(Long.valueOf(idProd)).getCantidad();
					String res = matPrimaE.getNombre()+ "\n Mat. Prima \n Faltan:" + f;
					System.out.println(res);
					return res;					
  			}
					
				if(aprov=="s"){
					RemMPEntity Reemplazo = new RemMPEntity();
					Reemplazo.setIdProducto(Long.valueOf(idProd));
					Reemplazo.setIdDetallePedido(idDetallePedido);
					Reemplazo.setCantidad(Float.valueOf(cantidad));
					Reemplazo.setIdRefaccion(Long.valueOf(idrefaccion));
					Reemplazo.setIdMateriaOld(Long.valueOf(idmateriaold));
					Reemplazo.setObservacion(observacion);
					Reemplazo.setIdMateria(Long.valueOf(idMP));
					session.save(Reemplazo);
				}
				
				
			}
			session.flush();
			session.getTransaction().commit();
			 //<--Realizamos commit de operacion en db
		errRslt = null;
			}
			
		}catch (Exception e) {
			
	  		session.getTransaction().rollback();
			errRslt = e.getMessage();
			System.out.println("Error en agrega Requisicon con detalle implement: " + errRslt);
			
		}
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		System.out.println(errRslt);
		return errRslt;
	}
	
	
}
